import { defineStore } from "pinia";
import { ref, watch } from "vue";
import type { LiveDataStore } from "./LiveDataStore";
import type { PlayerStore } from "@/store/usePlayer";
export const useRedPacketStore = defineStore("redPacket", () => {
  const isComplete = ref(false);
  const setIsComplete = (value: boolean) => {
    isComplete.value = value;
  };
  const initWatcher = (
    liveDataStore: LiveDataStore,
    playerStore: PlayerStore
  ) => {
    const { roomData, roomWatchData } = liveDataStore;
    // 如果未配置时长红包或红包已发放，则不进行监听
    if (
      (roomData.redPacket.openRedPacket !== 2 &&
        roomData.redPacket.openRedPacket !== 3 &&
        roomData.redPacket.openRedPacket !== 4) ||
      roomWatchData.completedRewardState !== 0 ||
      roomWatchData.combineRewardState !== 0
    ) {
      return;
    }
    // 监听红包发放
    watch(
      () => playerStore.realProgress,
      (newProgress, oldProgress) => {
        if (!newProgress || !roomData.redPacket?.playTime) return;

        const newTime = Math.floor(newProgress);
        const oldTime = Math.floor(oldProgress);

        if (newTime >= roomData.redPacket.playTime && newTime !== oldTime) {
          if (isComplete.value) {
            return;
          }
          console.log("时长满足");
          setIsComplete(true);
        }
      }
    );
  };
  return {
    isComplete,
    setIsComplete,
    initWatcher
  };
});
export type RedPacketStore = ReturnType<typeof useRedPacketStore>;
